const express = require('express')
const axios = require('axios')
const path = require('path');
const app = express()
const port = 3000
const APPID = 'e39397cc'
const APISecret = 'MDc2MDZiOTgwZDExM2YwZWZhOTgwMzcz'
const APIKey = '0e5e11f2551b32e85d68e15ed39a446a'
const httpUrl = "https://spark-api.cn-huabei-1.xf-yun.com/v2.1/tti"
const CryptoJS = require('./static/crypto-js/crypto-js.js')
const parser = require('./static/fast-xml-parser/src/parser')
const base64 = require('base-64')
app.use(function(req,res,next){
  // req:表示请求对象
  // res:表示响应对象
  // next:表示下一步
  // *：通配符
  res.setHeader('Access-Control-Allow-Origin','*')//允许哪些域名请求我
  res.setHeader('Access-Control-Request-Methods','GET,POST,PUT,DELETE,OPTIONS')//允许哪些请求方式可以请求我
  res.setHeader('Access-Control-Allow-Headers','x-requested-with,content-type')//允许携带哪些请求头信息
  
  // **************上面的代码一写那么就等于这个服务器开启了跨域资源共享
  next()
})
app.get('/getimage', async (req, res) => {

  const url = await getWebSocketUrl()
  const queryParams = req.query;
  // 参数
  let params = {
    "header": {
      "app_id": APPID,
      "uid": "aef9f963-7"
    },
    "parameter": {
      "chat": {
        "domain": 'general',
        "width": 512,
        "height": 512
      }
    },
    "payload": {
      "message": {
        "text": [
          {
            "role": "user",
            "content": queryParams.text
          }
        ]
      }
    }
  };
  axios({
    method: 'post',
    url: url,
    data: params,
    headers: {
      'Content-Type': 'application/json',
    },
  })
    .then((response) => {
      console.log(response.data);
      res.send(response.data.payload.choices.text)
    })
})
// 鉴权 --- 通用的方法
function getWebSocketUrl() {
  var httpUrlHost = (httpUrl).substring(8, 40);
  var httpUrlPath = (httpUrl).substring(40);
  return new Promise((resolve, reject) => {
    var url = "https://" + httpUrlHost + httpUrlPath;
    var host = "spark-api.cn-huabei-1.xf-yun.com";
    var date = new Date().toGMTString();
    var algorithm = "hmac-sha256";
    var headers = "host date request-line";
    var signatureOrigin = `host: ${host}\ndate: ${date}\nPOST ${httpUrlPath} HTTP/1.1`;
    var signatureSha = CryptoJS.HmacSHA256(signatureOrigin, APISecret);
    var signature = CryptoJS.enc.Base64.stringify(signatureSha);
    var authorizationOrigin =
      `api_key="${APIKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
    var authorization = base64.encode(authorizationOrigin);
    url = `${url}?authorization=${authorization}&date=${encodeURI(date)}&host=${host}`;

    resolve(url); // 主要是返回地址
  });
}
app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})